import {Component, OnInit, OnDestroy} from '@angular/core';
import {Router, NavigationEnd} from '@angular/router';
import {UserService} from '@kylin/user';
import {HomeService} from './home.service';
import {ConfigService} from '@kylin/config';
import {RouterService} from '@kylin/router';
import {NzModalRef, NzModalService} from 'ng-zorro-antd';
import {HttpService} from '@kylin/http';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import * as _ from 'lodash';
import {Subscription} from 'rxjs';

@Component({
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.less']
})

export class HomeComponent implements OnInit, OnDestroy {
    sidebarMenuList: Array<any>;
    avatar = '../../assets/img/avatar.png';
    imgHostname = this.httpConfigService.imgHostname;
    dropDownVisible: boolean; // 下拉菜单状态,true为打开
    nzWidth = 200;
    nzInlineCollapsed = false;
    confirmModal: NzModalRef; // For testing by now
    accountSettingsVisible = false;
    accountForm: FormGroup;
    passwordForm: FormGroup;
    user: any = {};
    accountNzSelectedIndex = 0;
    accountSettingsLoading = false;
    private _nzCollapsed = false;

    isFullscreen = true;
    rooterChange: Subscription;

    get nzCollapsed() {
        return this._nzCollapsed;
    }

    set nzCollapsed(value) {
        this._nzCollapsed = value;
        this.homeService.$changeNzCollapsedObservable(value);
    }

    constructor(
        public homeService: HomeService,
        private httpConfigService: ConfigService,
        private router: Router,
        private routerService: RouterService,
        private modal: NzModalService,
        private http: HttpService,
        private fb: FormBuilder,
        private userService: UserService,
        private nzMessageService: NzMessageService
    ) {

    }

    ngOnInit() {
        this.accountForm = this.fb.group({
            nickname: [null, [Validators.required]]
        });
        this.passwordForm = this.fb.group({
            oldPassword: [null, [Validators.required]],
            newPassword: [null, [Validators.required]]
        });
        this.sidebarMenuList = this.homeService.getSidebarMenuData();
        this.fetchPersInfo();
        this.homeService.fullscreenObservable.subscribe((value: boolean) => {
            this.isFullscreen = value;
            setTimeout(() => {
                this.nzCollapsed = false;
            }, 0)
        });
        this.listenRouterChange();
    }

    ngOnDestroy() {
        if (this.rooterChange) {
            this.rooterChange.unsubscribe();
        }
    }

    listenRouterChange() {
        this.rooterChange = this.router.events.subscribe((event) => {
            if (event instanceof NavigationEnd) {
                console.log(event);
                if (event.url === '/home/not-developed') {
                    this.nzMessageService.warning('不好意思,该功能暂未开通,敬请期待');
                }
            }
        });
    }

    fetchPersInfo() {
        this.userService.fetchPersInfo().then(res => {
            _.forIn(this.accountForm.controls, (value, key) => {
                this.accountForm.get(key).setValue(res[key]);
            });
            this.user = res;
        })
    }

    showConfirm(): void {
        this.confirmModal = this.modal.confirm({
            nzTitle: '退出确认',
            nzContent: '确定要退出登陆吗?',
            nzOnOk: () => {
                this.homeService.logout();
            }
        });
    }

    /**
     * 路由跳转
     * @param {string} path
     */
    public skip(path: string): void {
        this.routerService.navigate(path);
    }

    /**
     * 实现sider手风琴模式
     * @param {string} menuName
     */
    nzOpenChange(menuName: string): void {
        this.sidebarMenuList.forEach((value) => {
            value.isOpen = false;
            value.name === menuName ? value.isOpen = true : value.isOpen = false;
        });
    }

    accountSettingsCancel() {
        this.accountSettingsVisible = false;
    }

    accountSettingsOk(type: string) {
        this.accountSettingsLoading = true;
        switch (type) {
            case 'account':
                this.modifyPersInfo();
                break;
            case 'password':
                this.modifyPassword();
                break;
            default:
                console.error('accountSettingsOk出现了未知类型type,请检查此函数');
        }
    }

    modifyPassword() {
        this.http.put('/users/password', this.passwordForm.value)
            .then(res => {
                if (res.resp_code === '10000') {
                    this.nzMessageService.success('修改密码成功,请重新登录');
                    this.accountSettingsVisible = false;
                    this.passwordForm.reset();
                    this.routerService.navigate('/login');
                } else {
                    this.nzMessageService.error(res.resp_msg);
                }
                this.accountSettingsLoading = false;
            })
            .catch(err => {
                this.nzMessageService.error(err.error.resp_msg || '修改密码失败');
                this.accountSettingsLoading = false;
            })
    }

    modifyPersInfo() {
        this.http.put('/users/me', this.accountForm.value)
            .then(res => {
                if (res.resp_code === '10000') {
                    this.nzMessageService.success('修改信息成功');
                    this.accountSettingsVisible = false;
                    this.accountForm.reset();
                    this.fetchPersInfo();
                } else {
                    this.nzMessageService.error(res.resp_msg);
                }
                this.accountSettingsLoading = false;
            })
            .catch(err => {
                this.nzMessageService.error(err.error.resp_msg || '修改信息失败');
                this.accountSettingsLoading = false;
            })
    }

}
